 
package com.zdkj.subway.rca.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.util.DateUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zdkj.common.core.exceltools.ExcelUtil;
import com.zdkj.common.core.exceltools.IExcelParser;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.alibaba.excel.EasyExcel;


import com.zdkj.common.core.util.SpringContextHolder;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.rca.entity.SwCkBackElectronicBill;
import com.zdkj.subway.rca.entity.SwCkBackElectronicBillCcbTmp;
import com.zdkj.subway.rca.entity.SwCkCcbParsingRule;
import com.zdkj.subway.rca.mapper.SwCkBackElectronicBillCcbTmpMapper;
import com.zdkj.subway.rca.service.SwCkBackElectronicBillCcbTmpService;
import com.zdkj.subway.rca.service.SwCkBackElectronicBillService;
import com.zdkj.subway.rca.service.SwCkCcbParsingRuleService;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.ZoneId;
import java.util.*;

/**
 * 建设银行电子账单临时表
 *
 * @author stw
 * @date 2020-09-27 11:58:59
 */
@Service
public class SwCkBackElectronicBillCcbTmpServiceImpl extends ServiceImpl<SwCkBackElectronicBillCcbTmpMapper, SwCkBackElectronicBillCcbTmp> implements SwCkBackElectronicBillCcbTmpService {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(SwCkBackElectronicBillCcbTmpServiceImpl.class);

    @Autowired
    private SwCkBackElectronicBillService swCkBackElectronicBillService;
    @Autowired
    private SwCkCcbParsingRuleService swCkCcbParsingRuleService;

/*
    @Override
    public Boolean saveBatchWithExcel(final File excelFile) throws Exception {
        final Workbook workbook = ExcelUtil.chooseWorkbook(excelFile);
        final Sheet sheet = workbook.getSheetAt(0);
        final IExcelParser excelParser = SpringContextHolder.getBean("commonExcelParse");
        final List<SwCkBackElectronicBillCcbTmp> swCkBackElectronicBillCcbTmps = excelParser.parse(sheet, new SwCkBackElectronicBillCcbTmp());
        if (CollectionUtil.isNotEmpty(swCkBackElectronicBillCcbTmps)) {
            List<SwCkBackElectronicBillCcbTmp> listSwCkBackElectronicBillCcbTmp = new ArrayList<>();
            MultipartFileToFile.delteTempFile(excelFile);
            for(SwCkBackElectronicBillCcbTmp swCkBackElectronicBillCcbTmp : swCkBackElectronicBillCcbTmps){
                final SwCkBackElectronicBillCcbTmp obj =  ObjectUtils.getDefaultObj(SwCkBackElectronicBillCcbTmp.class);
                BeanUtils.copyProperties(swCkBackElectronicBillCcbTmp,obj,"deptId","creatorId","creatorName");
                checkErr(obj);
                listSwCkBackElectronicBillCcbTmp.add(obj);
            }
            Map<String,Object> columnMap = new HashMap<>();
            columnMap.put("CREATOR_ID", listSwCkBackElectronicBillCcbTmp.get(0).getCreatorId());
            this.baseMapper.deleteByMap(columnMap);
            return this.saveBatch(listSwCkBackElectronicBillCcbTmp);
        }

        return false;
    }*/
	@Override
    public Boolean saveBatchWithExcel(final File excelFile) throws Exception {
		 List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet().headRowNumber(1).doReadSync();
        if (CollectionUtil.isNotEmpty(listMap)) {
            List<SwCkBackElectronicBillCcbTmp> listDb = new ArrayList<>();
            MultipartFileToFile.delteTempFile(excelFile);
            for (int m = 0; m < listMap.size(); m++) {
                Map<Integer, String> data = listMap.get(m);
                // 返回每条数据的键值对 表示所在的列 和所在列的值
                LOGGER.info("读取到数据:{}", JSON.toJSONString(data));
				
                SwCkBackElectronicBillCcbTmp tmpObj = new SwCkBackElectronicBillCcbTmp();
				tmpObj.setReceiveAccount(data.get(0));
				tmpObj.setReceiveAccountName(data.get(1));
				tmpObj.setTransactionTimeTmp(data.get(2));
				tmpObj.setTransactionAmounTmp(data.get(4));
				tmpObj.setCurrency(data.get(6));
				tmpObj.setAccountName(data.get(7));
				tmpObj.setPayerAccount(data.get(8));
				tmpObj.setPayerAccountName(data.get(9));
				tmpObj.setRemarks(data.get(12));
                

                if (StringUtils.isEmpty(tmpObj.getReceiveAccount())
                        || StringUtils.isEmpty(tmpObj.getReceiveAccountName())
                        || StringUtils.isEmpty(tmpObj.getReceiveAccount())
					    || StringUtils.isEmpty(tmpObj.getTransactionTimeTmp())
					    || StringUtils.isEmpty(tmpObj.getTransactionAmounTmp())
                        || StringUtils.isEmpty(tmpObj.getPayerAccount())
                        ) {
                    continue;
                }
                /*
				if (!parseDate(tmpObj.getTradeDateTmp())) {
                    continue;
                }*/
				final SwCkBackElectronicBillCcbTmp obj =  ObjectUtils.getDefaultObj(SwCkBackElectronicBillCcbTmp.class);
                BeanUtils.copyProperties(tmpObj,obj,"deptId","creatorId","creatorName");
                checkErr(obj);
                listDb.add(obj);              

            }
			Map<String,Object> columnMap = new HashMap<>();
            columnMap.put("CREATOR_ID", listDb.get(0).getCreatorId());
            this.baseMapper.deleteByMap(columnMap);
            return this.saveBatch(listDb);         
        }

        return false;
    }


    private void checkErr(SwCkBackElectronicBillCcbTmp obj) {
        //更新字段
        String  transactionTimeTmp = obj.getTransactionTimeTmp();
        try {
            Date transactionTime = DateUtils.parseDate(transactionTimeTmp,"yyyyMMdd HH:mm:ss");
            obj.setTransactionTime(transactionTime.toInstant().atZone( ZoneId.systemDefault() ).toLocalDateTime());
            obj.setRecordTime((transactionTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()).plusDays(-1));
        } catch (Exception e) {
            obj.setErrMsg("交易时间 为空或格式错误");
        }
        try {
            String transactionAmounTmp = obj.getTransactionAmounTmp();
            BigDecimal transactionAmoun = new BigDecimal(transactionAmounTmp);
            BigDecimal  num = new BigDecimal("100");
            //transactionAmoun = transactionAmoun.multiply(num);四舍五入后再截取
			transactionAmoun = transactionAmoun.multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
            obj.setTransactionAmoun(transactionAmoun.longValue());
        } catch (Exception e) {
            obj.setErrMsg("贷方发生额（收入） 为空或格式错误");
        }

        SwCkCcbParsingRule swCkCcbParsingRule = new SwCkCcbParsingRule();
        if (StringUtils.isEmpty(obj.getAccountName()) || StringUtils.isEmpty(obj.getRemarks())) {
            obj.setErrMsg("对方户名或备注 为空，不符合解析规则");
        }

        swCkCcbParsingRule.setAccountName(obj.getAccountName());
        swCkCcbParsingRule.setRemarks(obj.getRemarks().contains("0144银联代理商户入帐")? "0144银联代理商户入帐" : (obj.getRemarks().contains("0141银联代理商户入帐")? "0141银联代理商户入帐" : obj.getRemarks()));
        SwCkCcbParsingRule newSwCkCcbParsingRule = swCkCcbParsingRuleService.getOne(Wrappers.query(swCkCcbParsingRule));
        if (newSwCkCcbParsingRule != null && StringUtils.isNotEmpty(newSwCkCcbParsingRule.getTruncateType()) && StringUtils.isNotEmpty(newSwCkCcbParsingRule.getPaymentType())) {
            obj.setTruncateType(newSwCkCcbParsingRule.getTruncateType());
            obj.setPaymentType(newSwCkCcbParsingRule.getPaymentType());
        } else {
            obj.setErrMsg("对方户名或备注 不符合解析规则");
        }

        //判断数据是否存在
        SwCkBackElectronicBill swCkBackElectronicBill = new SwCkBackElectronicBill();
        BeanUtils.copyProperties(obj,swCkBackElectronicBill,"deptId","creatorId","creatorName","createTime");
        List<SwCkBackElectronicBill> list = swCkBackElectronicBillService.list(Wrappers.query(swCkBackElectronicBill));
        if (list != null && !list.isEmpty()){
            obj.setErrMsg("数据已存在");
        }
    }

    @Override
    public void saveBatchWithExcelOk(Integer creatorId) {
        //导入先删除
        this.baseMapper.deleteBatchWithExcelOk(creatorId);
        //导入先删除再添加包括重复的
        this.baseMapper.saveBatchWithExcelOkRepeat(creatorId);
        //this.baseMapper.saveBatchWithExcelOk(creatorId);
        saveBatchWithExcelCancel(creatorId);
    }

    @Override
    public void saveBatchWithExcelCancel(Integer creatorId) {
        Map<String,Object> columnMap = new HashMap<>();
        columnMap.put("CREATOR_ID",creatorId);
        this.baseMapper.deleteByMap(columnMap);
    }

    @Override
    public void exportTamplates(HttpServletResponse response) {
        String  verifyConfirmName = "建设银行";
        String  tableName = "sw_ck_back_electronic_bill_ccb";

        BufferedInputStream br = null;
        OutputStream out = null;
        try {
            response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode(verifyConfirmName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xls");

            br =  new BufferedInputStream(this.getClass().getResourceAsStream("/static/excel/template/import/" + tableName + ".xls"));

            byte[] buf = new byte[1024];
            int len = 0;

            out = response.getOutputStream();
            while ((len = br.read(buf)) > 0) {
                out.write(buf, 0, len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(out != null) {
                try {
                    out.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            if(br != null){
                try {
                    br.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }
}
